package mysql

import (
	"core/env"
	"core/graylog"
	"core/utils"
	"fmt"
	"os"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
)

var X *xorm.Engine

func InitXorm() (err error) {
	X, err = xorm.NewEngine(env.Conf.XOrmDriverName, env.Conf.XOrmDataSourceName)
	if err != nil {
		return
	}
	X.SetMaxOpenConns(1000)
	X.SetMaxIdleConns(30)
	X.SetConnMaxLifetime(time.Second)
	err = X.Ping()
	if err != nil {
		return fmt.Errorf("xorm ping error, %+v", err)
	}
	go ping(X)
	// debug 显示sql语句
	//X.ShowSQL(true)

	//ExportSQL()
	return
}

func ping(engine *xorm.Engine) {
	defer utils.CatchPanic()
	ticker := time.NewTicker(time.Second * 30)
	for {
		select {
		case <-ticker.C:
			err := engine.Ping()
			if err != nil {
				graylog.Info("mysql连接异常", graylog.M{
					"errInfo": err.Error(),
				})
			}
		}
	}
}

// 导出数据
func ExportSQL() (err error) {
	file, err := os.OpenFile("tms.sql", os.O_RDWR|os.O_CREATE, 0777)
	if err != nil {
		return
	}
	defer file.Close()
	err = X.DumpAll(file)
	return
}

func ImportSQL() (err error) {
	file, err := os.OpenFile("tms.sql", os.O_RDWR|os.O_CREATE, 0777)
	if err != nil {
		return
	}
	defer file.Close()
	results, err := X.Import(file)
	if err != nil {
		return
	}
	utils.Info(results)
	return
}
